import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:auto_orientation/auto_orientation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/utils/sp_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/view/home/blue/view_ble_info.dart';
import 'package:flutter_chip/view/home/blue/view_ble_set.dart';
import 'package:flutter_chip/view/home/blue/view_scan.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:flutter_lifecycle_state/flutter_lifecycle_state.dart';

class BluePage extends StatefulWidget {
  @override
  _BluePageState createState() => _BluePageState();
}

class _BluePageState extends StateWithLifecycle<BluePage> {
  BluetoothConnection connection;
  String name = "未连接";
  String status = "";
  BluetoothDevice device;
  String sendValue;
  String recvValue1;
  String recvValue2;
  Map<String, String> config = Map();

  @override
  void initState() {
    super.initState();
    _initBle();
  }

  @override
  void onResume() {
    super.onResume();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeLeft,
    ]);
    _configInit();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        centerTitle: true,
        backgroundColor: Theme.of(context).canvasColor,
        title: _titleWidget(),
        actions: <Widget>[_popupMenuBtn()],
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            _directionWidget(),
            _centerWidget(),
            _rightWidget(),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    if (null != connection) {
      connection.dispose();
    }
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
  }

  Widget _popupMenuBtn() {
    Color color = Theme.of(context).cardColor;
    return PopupMenuButton(
      itemBuilder: (BuildContext context) {
        return <PopupMenuItem<String>>[
          PopupMenuItem<String>(
            value: "01",
            child: Row(
              children: <Widget>[
                Icon(Icons.bluetooth_connected, color: color),
                SizedBox(width: 6),
                Text(
                  "设备连接",
                  style: TextStyle(color: color),
                ),
              ],
            ),
          ),
          PopupMenuItem<String>(
            value: "02",
            child: Row(
              children: <Widget>[
                Icon(Icons.settings, color: color),
                SizedBox(width: 6),
                Text("参数设置", style: TextStyle(color: color)),
              ],
            ),
          ),
          PopupMenuItem<String>(
            value: "03",
            child: Row(
              children: <Widget>[
                Icon(Icons.error, color: color),
                SizedBox(width: 6),
                Text("功能说明", style: TextStyle(color: color)),
              ],
            ),
          ),
        ];
      },
      color: Color(0xff4B4B4B),
      offset: Offset(100, 100),
      onSelected: (String value) {
        switch (value) {
          case "01":
            Navigator.push(context, RouteSlide(BleScanPage())).then((value) {
              if (null == value) {
                return;
              }
              device = value;
              _startConnect();
            });
            break;
          case "02":
            Navigator.push(context, RouteSlide(BleSetting()));
            break;
          case "03":
            Navigator.push(context, RouteSlide(BlueInfo()));
            break;
        }
      },
    );
  }

  ///顶部标题栏
  Widget _titleWidget() {
    return GestureDetector(
      onTap: () => _startConnect(),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            name,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
            ),
          ),
          Text(
            status,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  ///左侧方向键
  Widget _directionWidget() {
    double width = max(Comm.screenWidth / 3, Comm.screenHeight / 3);
    return SizedBox(
      width: width,
      height: width,
      child: Card(
        elevation: 4.0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(Comm.screenWidth / 6),
          ),
        ),
        child: Stack(
          children: <Widget>[
            Align(
              alignment: Alignment.topCenter,
              child: IconButton(
                icon: Icon(Icons.keyboard_arrow_up),
                onPressed: () {
                  _sendData(config["dir_up"]);
                },
              ),
            ),
            Align(
              alignment: Alignment.centerLeft,
              child: IconButton(
                icon: Icon(Icons.keyboard_arrow_left),
                onPressed: () {
                  _sendData(config["dir_left"]);
                },
              ),
            ),
            Align(
              alignment: Alignment.center,
              child: SizedBox(
                child: Card(
                  elevation: 4.0,
                  child: FlatButton(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(
                        Radius.circular(30.0),
                      ),
                    ),
                    onPressed: () => _sendData(config["dir_center"]),
                    padding: EdgeInsets.all(0),
                    child: Text(
                      config["dir_label"] ?? "",
                      style: TextStyle(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(
                      Radius.circular(30.0),
                    ),
                  ),
                ),
                width: 60,
                height: 60,
              ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: IconButton(
                icon: Icon(Icons.keyboard_arrow_down),
                onPressed: () {
                  _sendData(config["dir_down"]);
                },
              ),
            ),
            Align(
              alignment: Alignment.centerRight,
              child: IconButton(
                padding: EdgeInsets.all(0),
                icon: Icon(Icons.keyboard_arrow_right),
                onPressed: () {
                  _sendData(config["dir_right"]);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///中间按钮
  Widget _centerWidget() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Column(
          children: <Widget>[
            Text(
              config["label_recv1"] ?? "",
              style: TextStyle(
                color: Theme.of(context).hintColor,
                fontWeight: FontWeight.w400,
                fontSize: 12,
              ),
            ),
            Text(
              recvValue1 ?? "无",
              style: TextStyle(
                color: Theme.of(context).accentColor,
                fontWeight: FontWeight.w600,
                fontSize: 18,
              ),
            )
          ],
        ),
        Column(
          children: <Widget>[
            Text(
              config["label_recv2"] ?? "",
              style: TextStyle(
                color: Theme.of(context).hintColor,
                fontWeight: FontWeight.w400,
                fontSize: 12,
              ),
            ),
            Text(
              recvValue2 ?? "无",
              style: TextStyle(
                color: Theme.of(context).accentColor,
                fontWeight: FontWeight.w600,
                fontSize: 18,
              ),
            )
          ],
        ),
        Column(
          children: <Widget>[
            Text(
              "发送键值:",
              style: TextStyle(
                color: Theme.of(context).hintColor,
                fontWeight: FontWeight.w400,
                fontSize: 12,
              ),
            ),
            Text(
              sendValue ?? "无",
              style: TextStyle(
                color: Theme.of(context).accentColor,
                fontWeight: FontWeight.w600,
                fontSize: 18,
              ),
            ),
          ],
        ),
      ],
    );
  }

  ///右边按钮
  Widget _rightWidget() {
    double width = max(Comm.screenWidth / 3, Comm.screenHeight / 3);
    return Container(
      width: width,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              _btnWidget(config["label_1"], config["send_1"]),
              _btnWidget(config["label_2"], config["send_2"]),
              _btnWidget(config["label_3"], config["send_3"]),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              _btnWidget(config["label_4"], config["send_4"]),
              _btnWidget(config["label_5"], config["send_5"]),
              _btnWidget(config["label_6"], config["send_6"]),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              _btnWidget(config["label_7"], config["send_7"]),
              _btnWidget(config["label_8"], config["send_8"]),
              _btnWidget(config["label_9"], config["send_9"]),
            ],
          )
        ],
      ),
    );
  }

  Widget _btnWidget(String key, String sendValue) {
    var shape = RoundedRectangleBorder(
      borderRadius: BorderRadius.all(
        Radius.circular(32.0),
      ),
    );
    var style = TextStyle(fontSize: 12, fontWeight: FontWeight.w600);
    return SizedBox(
      width: 64,
      height: 64,
      child: Card(
        shape: shape,
        elevation: 4,
        child: FlatButton(
          shape: shape,
          onPressed: () => _sendData(sendValue),
          padding: EdgeInsets.all(0),
          child: Text(key ?? "", style: style),
        ),
      ),
    );
  }

  ///资源初始化
  void _initBle() async {
    bool isAvailable = await FlutterBluetoothSerial.instance.isAvailable;
    if (!isAvailable) {
      Toast.show("当前设备不支持蓝牙");
      return;
    }
    bool isEnable = await FlutterBluetoothSerial.instance.isEnabled;
    if (!isEnable) {
      FlutterBluetoothSerial.instance.requestEnable().then((enable) {
        AutoOrientation.landscapeAutoMode();
        setState(() {
          if (enable) {
            status = "蓝牙已打开";
          } else {
            status = "蓝牙未开启";
          }
        });
      });
    } else {
      status = "蓝牙已打开";
    }
  }

  ///初始化界面参数
  void _configInit() async {
    config.clear();
    config.addAll(await SpUtils.getBleConfig());
    setState(() {});
  }

  ///开始连接
  void _startConnect() async {
    if (null == device) {
      Toast.show("请先选择要连接的设备");
      return;
    }
    try {
      if (null != connection) {
        connection.dispose();
        connection = null;
      }
      setState(() {
        status = "连接中...";
        name = device.name ?? "未知设备";
      });
      connection = await BluetoothConnection.toAddress(device.address);
      if (!connection.isConnected) {
        setState(() {
          status = "连接不成功";
        });
      }
      setState(() {
        status = "已连接：${device.address}";
      });
      String tmpData = "";
      connection.input.listen((Uint8List data) {
        tmpData = tmpData + ascii.decode(data);
        print("总数据：$tmpData");
        if (tmpData.contains("\n") && tmpData.contains(",")) {
          tmpData.split("\n")[0].split(",").forEach((value) {
            if (value.contains(config["recv_start1"]) &&
                value.contains(config["recv_end1"])) {
              print("接收区1处理：$value");
              int start = value.indexOf(config["recv_start1"]) +
                  config["recv_start1"].length;
              int end = value.indexOf(config["recv_end1"]);
              if (start < end) {
                setState(() {
                  recvValue1 = value.substring(start, end);
                });
              }
            } else if (value.contains(config["recv_start2"]) &&
                value.contains(config["recv_end2"])) {
              print("接收区2处理：$value");
              int start = value.indexOf(config["recv_start2"]) +
                  config["recv_start2"].length;
              int end = value.indexOf(config["recv_end2"]);
              if (start < end) {
                setState(() {
                  recvValue2 = value.substring(start, end);
                });
              }
            }
          });
          tmpData = "";
        }
      }).onDone(() {
        print("处理完成");
      });
    } catch (exception) {
      print("连接异常：$exception");
      setState(() {
        status = "连接失败，点击重连";
      });
    }
  }

  ///发送数据
  void _sendData(String data) async {
    if (null == connection) {
      Toast.show("连接不可用");
      return;
    }
    setState(() {
      sendValue = data;
    });
    print("发送：$data---${data.codeUnits}");
    connection.output.add(utf8.encode(data));
    await connection.output.allSent;
    print("发送结束");
  }
}
